﻿using System.Linq.Expressions;
using BDQN.Entites;
using BDQN.IDAL;
using Microsoft.EntityFrameworkCore;

namespace BDQN.DAL
{
    public class BaseDal<T> : IBaseDal<T> where T : BaseEntity, new()
    {
        private BlogSysDbContext _ctx;

        public BaseDal(BlogSysDbContext ctx )
        {
            _ctx = ctx;
        }
        public async Task<int> AddAsync(T entity, bool isSaved = true)
        {
            _ctx.Entry(entity).State = EntityState.Added;
            return isSaved ? await _ctx.SaveChangesAsync() : 0;
        }

        public async Task<int> EditAsync(T entity, bool isSaved = true)
        {
            _ctx.Entry(entity).State = EntityState.Modified;
            return isSaved ? await _ctx.SaveChangesAsync() : 0;
        }

        public List<T> Query()
        {
            return _ctx.Set<T>().Where(t => t.DeleteId == 1).ToList();
        }

        public List<T> Query(Expression<Func<T, bool>> whereLambda)
        {
            return _ctx.Set<T>().Where(whereLambda).ToList();
        }

        public T Query(int id)
        {
            return _ctx.Set<T>().Find(id);
        }

        public async Task<List<T>> QueryAsync()
        {
            return await _ctx.Set<T>().Where(t => t.DeleteId == 1).ToListAsync();    
        }

        public async Task<List<T>> QueryAsync(Expression<Func<T, bool>> whereLambda)
        {
            return await _ctx.Set<T>().Where(whereLambda).ToListAsync();
        }

        public async Task<T> QueryAsync(int id)
        {
            return await _ctx.Set<T>().FindAsync(id);
        }

        public async Task<int> RemoveAsync(T entity, bool isSaved = true)
        {
            _ctx.Entry(entity).State = EntityState.Deleted;
            return isSaved ? await _ctx.SaveChangesAsync() : 0;
        }

        public async Task<int> SaveDataAsync()
        {
            return await _ctx.SaveChangesAsync();
        }
    }
}
